package hczc.longcai.com.hccrowdfunding.welcome;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import org.json.JSONException;

import hczc.longcai.com.hccrowdfunding.R;
import hczc.longcai.com.hccrowdfunding.application.BaseApplication;
import hczc.longcai.com.hccrowdfunding.home.HomeActivity;
import hczc.longcai.com.hccrowdfunding.utils.httputils.HttpPath;
import hczc.longcai.com.hccrowdfunding.utils.httputils.LoadDatas;
import hczc.longcai.com.hccrowdfunding.utils.json.ParseJSON;

/**
 * 启动页
 */
public class MainActivity extends AppCompatActivity {


    private static final String TAG = "MainActivity";
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            switch (what) {
                case 0:
                    startActivity(new Intent(MainActivity.this, HomeActivity.class));
                    finish();
                    break;
                case 1:
                    Toast.makeText(MainActivity.this,"请检查网络",Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(MainActivity.this,HomeActivity.class));
                    finish();
                    break;

            }

        }
    };
    private LoadDatas loadDatas;
    private ParseJSON parseJSON;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        loadDatas = new LoadDatas();

        new Thread(new Runnable() {
            @Override
            public void run() {
//                SystemClock.sleep(3000);
                try {
                    String url = HttpPath.URL;
                    byte[] datas = loadDatas.getDatas(url);
                    String json = new String(datas, 0, datas.length);
                    ParseJSON.parseIndex(json);
                    handler.sendEmptyMessage(0);
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (NullPointerException e) {
                    Message message = handler.obtainMessage();
                    message.obj = "请检查网络";
                    message.what = 1;
                    handler.sendMessage(message);
                }

            }
        }).start();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
